package com.wwwarehouse.common.activity.base;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.text.ClipboardManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ProgressDialogUtils;
import com.wwwarehouse.common.tools.SharedPreferencesHelper;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.XunfeiSpeekUtils;

import java.util.ArrayList;
import java.util.Random;

public abstract class BaseFragment extends Fragment implements PublicMethodInterface, PublicPowerInterface {
    public SharedPreferencesHelper sp;
    public Activity mActivity;
    public ProgressDialogUtils progressDialogUtils;
    BaseBroadcastReceiver receiver;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            sp = BaseApplication.sp;
            mActivity = getActivity();
            receiver = new BaseBroadcastReceiver();

            mActivity.registerReceiver(receiver, new IntentFilter("refreshClick"));

            mActivity.registerReceiver(receiver, new IntentFilter("titleBt1"));
            mActivity.registerReceiver(receiver, new IntentFilter("titleBt2"));
            mActivity.registerReceiver(receiver, new IntentFilter("titleBt3"));
            mActivity.registerReceiver(receiver, new IntentFilter("titleBt4"));

            mActivity.registerReceiver(receiver, new IntentFilter("title"));
            mActivity.registerReceiver(receiver, new IntentFilter("filterClick"));
            mActivity.registerReceiver(receiver, new IntentFilter("searchNoRealTimeClick"));
            mActivity.registerReceiver(receiver, new IntentFilter("searchOnRealTimeClick"));
            mActivity.registerReceiver(receiver, new IntentFilter("functionUnitClick"));
            mActivity.registerReceiver(receiver, new IntentFilter("cancelClick"));
            mActivity.registerReceiver(receiver, new IntentFilter("sortClick"));
        } catch (Exception e) {
			e.printStackTrace();
        }
    }

    @Override
    public void onDetach() {
		super.onDetach();
        if (mActivity != null && receiver != null) {
            mActivity.unregisterReceiver(receiver);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 退出时统一释放资源
        XunfeiSpeekUtils.getInstance().releaseResource();
    }

    @Override
    public void onResume() {
        super.onResume();
        setTitle();
    }

    // 代替findViewById
    public <T extends View> T findView(View v, int id) {
        return (T) v.findViewById(id);
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        Animation animation = null;
        if (enter) {
            // 进入动画
            animation = AnimationUtils.loadAnimation(mActivity, R.anim.comm_slide_in_from_right);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    requestDatas();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        } else {
            // 退出动画
            animation = AnimationUtils.loadAnimation(mActivity, R.anim.comm_slide_out_to_right);
        }

        return animation;
    }

    // 弹出Toast
    public void toastAtTop(final String msg) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToastAtTop(msg);
            }
        });
    }

    public void toastAtTop(final int resource) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToastAtTop(resource);
            }
        });
    }

    // 弹出Toast
    public void toast(final String msg) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(msg);
            }
        });
    }

    public void toast(final int resource) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(resource);
            }
        });
    }

    // 打开一个Activity传递一个Bundle
    public void startActivity(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            mActivity.startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    public void startActivity(String target, Bundle bundle, boolean finish) {
        if(target == null || "".equals(target)){
            if(LogUtils.isDebug()){
                toast(getString(R.string.arouter_mistake));
            }
            return ;
        }

        ARouter.getInstance()
                .build(target)
                .with(bundle)
                .withTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out)
                .navigation(mActivity);

        if (finish) {
            mActivity.finish();
        }
    }

    // 打开一个Activity传递一个Bundle
    public void startActivityWithoutFastClick(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        Intent intent = new Intent(mActivity, target);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        mActivity.startActivity(intent);
        mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        if (finish) {
            mActivity.finish();
        }
    }

    // 打开一个Activity传递一个字符串
    public void startActivity(Class<? extends Activity> target, String passDataKey, String value, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (passDataKey != null && value != null) {
                intent.putExtra(passDataKey, value);
            }
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    // 打开一个Activity传递一个boolean类型
    public void startActivity(Class<? extends Activity> target, String passDataKey, boolean value, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (passDataKey != null) {
                intent.putExtra(passDataKey, value);
            }
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    // 打开一个Activity传递一个ArrayList
    public void startActivity(Class<? extends Activity> target, String passDataKey, ArrayList<String> list, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (passDataKey != null) {
                intent.putStringArrayListExtra(passDataKey, list);
            }
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    public void pushFragment(Fragment fragment) {
        ((BaseCardDeskActivity) mActivity).pushFragment(fragment);
    }

    public void pushFragment(String target, Bundle bundle) {
        ((BaseCardDeskActivity) mActivity).pushFragment(target, bundle);
    }

    public void popFragment() {
        ((BaseCardDeskActivity) mActivity).popFragment();
    }

    public Fragment peekFragment() {
        return ((BaseCardDeskActivity) mActivity).peekFragment();
    }

    // 打开一个Activity
    public void startActivityForResult(Class<? extends Activity> target, int requestCode, Bundle bundle) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            startActivityForResult(intent, requestCode);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        }
    }

    public void finishActivity() {
        mActivity.finish();
        mActivity.overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
    }

    // 隐藏软键盘
    public void hideSoftKeyBoard(View view) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏键盘
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    // 显示软键盘
    public void showSoftKeyBoard(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        //显示键盘
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public DisplayMetrics getScreenParams() {
        DisplayMetrics dm = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    // 保存到剪切板
    public void saveToClipboard(String text) {
        ClipboardManager c = (ClipboardManager) mActivity.getSystemService(Service.CLIPBOARD_SERVICE);
        c.setText(text);
        toast("已复制到剪切板");
    }

    // 显示ProgressDialog
    public void showProgressDialog() {
        progressDialogUtils = ProgressDialogUtils.show(mActivity);
    }

    // 显示ProgressDialog
    public void showProgressDialog(String text) {
        progressDialogUtils = ProgressDialogUtils.show(mActivity,text);
    }

    // 隐藏ProgressDialog
    public void dismissProgressDialog() {
        if (progressDialogUtils != null &&  progressDialogUtils.isShowing()) {
            progressDialogUtils.dismiss();
        }
    }

    //改变progress上文字
    public void setProgressDialogText(String text){
        if (progressDialogUtils != null){
            progressDialogUtils.setTextHint(text);
        }
    }

    //获取随机数， 参数为返回随机数的长度
    public String generateRandomString(int length) {
        String allChar = "0123456789abcdefghijklmnopqrstuvwxyz";
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString();
    }

    class BaseBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if ("refreshClick".equals(action)) {
                refreshClick();
            } else if ("titleBt1".equals(action)) {
                titleBt1Click();
            } else if ("titleBt2".equals(action)) {
                titleBt2Click();
            } else if ("titleBt3".equals(action)) {
                titleBt3Click();
            } else if ("titleBt4".equals(action)) {
                titleBt4Click();
            } else if ("title".equals(action)) {
                setTitle();
            } else if ("filterClick".equals(action)) {
                filterClick();
            } else if ("searchNoRealTimeClick".equals(action)) {
                String text = intent.getStringExtra(action);
                searchNoRealTimeClick(text);
            } else if ("searchOnRealTimeClick".equals(action)) {
                String text = intent.getStringExtra(action);
                searchOnRealTimeClick(text);
            } else if ("functionUnitClick".equals(action)) {
                TextView functionUnitTxt = ((BaseCardDeskActivity) mActivity).getFunctionUnitTextView();
                functionUnitClick(functionUnitTxt);
            } else if ("cancelClick".equals(action)) {
                cancelClick();
            } else if ("sortClick".equals(action)) {
                ImageView sortImg = ((BaseCardDeskActivity) mActivity).getSortImageView();
                sortClick(sortImg);
            }
        }
    }

	public  <T extends View> T $(@IdRes int resId) {
		return (T) getView().findViewById(resId);
	}


	public <T extends View> T getElementView(@IdRes int resId) {
		return (T) getView().findViewById(resId);
	}

    /**
     * 刷新
     */
    @Override
    public void refreshClick() {

    }

    /**
     * Title上四个自定义按钮
     */
    @Override
    public void titleBt1Click() {

    }

    @Override
    public void titleBt2Click() {

    }

    @Override
    public void titleBt3Click() {

    }

    @Override
    public void titleBt4Click() {

    }

    /**
     * 筛选按钮的点击事件
     */
    @Override
    public void filterClick() {

    }

    /**
     * 非实时搜索的点击事件(点击键盘右下方的搜索按钮进行搜索操作)
     * @param text  内容
     */
    @Override
    public void searchNoRealTimeClick(String text) {

    }

    /**
     * 实时搜索(输入内容进行搜索操作)
     * @param text  内容
     */
    @Override
    public void searchOnRealTimeClick(String text) {

    }

    /**
     * 选择业务单位按钮的点击事件
     */
    @Override
    public void functionUnitClick(View anchor) {

    }

    /**
     * 取消按钮的点击事件
     */
    @Override
    public void cancelClick() {

    }

    /**
     * 排序按钮的点击事件
     */
    @Override
    public void sortClick(View anchor) {

    }
}
